package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: WangHongKun
 * @Date: 2022/9/22 16:58
 * @Email: 2028911483@qq.com
 * @Phone: 18683977706
 */

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkSpaceService workSpaceService;

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin , LocalDate end) {
        List<LocalDate>  dateList =new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);

        }
        List<Double>  turnOverList  = new ArrayList<>();
        for(LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Double sum = orderMapper.getSumByStatusAndTime(Orders.COMPLETED, beginTime, endTime);
            if(sum == null){
                turnOverList.add(0.0);
            }
            else{
                turnOverList.add(sum);
            }
        }
        return new TurnoverReportVO(StringUtils.join(dateList,","),StringUtils.join(turnOverList,","));

    }

    @Override
    @Transactional
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate>  dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin =begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer>  newUserList = new ArrayList<>();
        List<Integer>  totalUserList = new ArrayList<>();
        for(LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer newUser = userMapper.getNewUser(beginTime, endTime);
            Integer totalUser = userMapper.getTotalUser(endTime);
            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }
        return new UserReportVO(StringUtils.join(dateList,","),StringUtils.join(totalUserList,","),StringUtils.join(newUserList,","));

    }

    @Override
    @Transactional
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate>  dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin =begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer>  orderCountList = new ArrayList<>();
        List<Integer>  validOrderCountList = new ArrayList<>();
        for(LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer everyDayOrders = orderMapper.getEveryDayOrders(beginTime, endTime);
            Integer everyValidDayOrders = orderMapper.getEveryValidDayOrders(Orders.COMPLETED, beginTime, endTime);
            orderCountList.add(everyDayOrders);
            validOrderCountList.add(everyValidDayOrders);
        }
        Integer totalOrderCount = orderMapper.getEveryDayOrders(null, LocalDateTime.of(end, LocalTime.MAX));
        Integer validOrderCount = orderMapper.getEveryValidDayOrders(Orders.COMPLETED, null, LocalDateTime.of(end, LocalTime.MAX));
        if (totalOrderCount ==0){
            return new OrderReportVO(StringUtils.join(dateList,","),StringUtils.join(orderCountList,",")
                    ,StringUtils.join(validOrderCountList,","),totalOrderCount,validOrderCount,0.0);
        }
        Double Rate = (double) validOrderCount / totalOrderCount;
        return new OrderReportVO(StringUtils.join(dateList,","),StringUtils.join(orderCountList,",")
                ,StringUtils.join(validOrderCountList,","),totalOrderCount,validOrderCount,Rate);
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderDetailMapper.getSalseTop10(beginTime, endTime, Orders.COMPLETED);
        List<String> nameList = new ArrayList<>();
        List<Integer>  numberList = new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO : salesTop10){
            numberList.add(goodsSalesDTO.getNumber());
            nameList.add(goodsSalesDTO.getName());
        }

        if(salesTop10 == null && salesTop10.size() <=0){
            throw new OrderBusinessException("目前暂未有商品售出");
        }
        return new SalesTop10ReportVO(StringUtils.join(nameList,","),StringUtils.join(numberList,","));
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) throws IOException {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        BusinessDataVO businessData = workSpaceService.getTodayBusinessData1(LocalDateTime.of(begin,LocalTime.MIN),LocalDateTime.of(end,LocalTime.MAX));

        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        XSSFWorkbook excel = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = excel.getSheet("Sheet1");
        sheet.getRow(1).getCell(0).setCellValue(begin.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "至" + end.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        XSSFRow row = sheet.getRow(3);

        //获取单元格
        row.getCell(2).setCellValue(businessData.getTurnover());
        row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
        row.getCell(6).setCellValue(businessData.getNewUsers());
        row = sheet.getRow(4);
        row.getCell(2).setCellValue(businessData.getValidOrderCount());
        row.getCell(4).setCellValue(businessData.getUnitPrice());
        for (int i = 0; i < 30; i++) {
            LocalDate date = begin.plusDays(i);
            //准备明细数据
            businessData = workSpaceService.getTodayBusinessData1(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            row = sheet.getRow(7 + i);
            row.getCell(1).setCellValue(date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(3).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessData.getUnitPrice());
            row.getCell(6).setCellValue(businessData.getNewUsers());
        }
        //通过输出流将文件下载到客户端浏览器中
        ServletOutputStream out = response.getOutputStream();
        excel.write(out);
        //关闭资源
        out.flush();
        out.close();
        excel.close();

    }


}
